package com.totowoo.shirodemo.security;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.totowoo.shirodemo.dao.UserDao;
import com.totowoo.shirodemo.model.User;

public class ShiroRealm extends AuthorizingRealm {

	private static final Logger log = LoggerFactory.getLogger(ShiroRealm.class);

	@Autowired
	private UserDao userDao;

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token0) throws AuthenticationException {

		UsernamePasswordToken token = (UsernamePasswordToken) token0;
		String username = token.getUsername();
		User loginUser = userDao.getUserByUsername(username);

		if (loginUser == null) {
			// throw new UnknownAccountException("用户:" + username + "不存在");
			log.info("用户:" + username + "不存在");
		}
		if (loginUser.getState() == 0) {
			// throw new LockedAccountException("用户:"+ username + "已被禁用");
			log.info("用户:" + username + "已被禁用");
		}

		ByteSource salt = ByteSource.Util.bytes(username);

		AuthenticationInfo info = new SimpleAuthenticationInfo(loginUser, loginUser.getPassword(), salt, getName());
		return info;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

		User user = (User) principals.getPrimaryPrincipal();

		log.info("PrincipalCollection:" + principals);

		Set<String> roles = userDao.getRoleCodesByUid(user.getId());
		info.addRoles(roles);

		Set<String> perms = userDao.getPermissionCodesByUid(user.getId());
		HashSet<String> permissions = new HashSet<>();

		for (String perm : perms) {
			if (perm.contains("p:")) {
				permissions.add(perm.replaceAll("p:", ""));
			} else {
				permissions.add(perm);
			}
		}
		info.addStringPermissions(permissions);

		return info;
	}

}
